<?php

declare (strict_types = 1);

namespace app\admin\model\admin;

use app\common\model\admin\UserRole as UserRoleModel;
use Exception;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 后台管理员用户角色模型
 * Class UserRole
 */
class UserRole extends UserRoleModel
{
    /**
     * 新增关系记录
     * @param int $storeUserId
     * @param array $roleIds
     * @return Collection
     * @throws Exception
     */
    public static function increased(int $storeUserId, array $roleIds): Collection
    {
        $data = [];
        foreach ($roleIds as $roleId) {
            $data[] = [
                'user_id' => $storeUserId,
                'role_id' => $roleId,
                'create_time' => time(),
            ];
        }
        return (new static)->saveAll($data);
    }

    /**
     * 更新关系记录
     * @param int $storeUserId
     * @param array $newRoles 新的角色集
     * @return array|bool|Collection
     * @throws Exception
     */
    public static function updates(int $storeUserId, array $newRoles): Collection|bool|array
    {
        // 已分配的角色集
        $assignRoleIds = self::getRoleIdsByUserId($storeUserId);
        // 找出删除的角色
        $deleteRoleIds = array_diff($assignRoleIds, $newRoles);
        if (!empty($deleteRoleIds)) {
            self::deleteAll([
                ['user_id', '=', $storeUserId],
                ['role_id', 'in', $deleteRoleIds]
            ]);
        }
        // 找出添加的角色
        $newRoleIds = array_diff($newRoles, $assignRoleIds);
        $data = [];
        foreach ($newRoleIds as $roleId) {
            $data[] = [
                'user_id' => $storeUserId,
                'role_id' => $roleId,
                'create_time' => time(),
            ];
        }
        return (new static)->saveAll($data);
    }

    /**
     * 获取指定管理员的所有角色id
     * @param int $storeUserId
     * @return array
     */
    public static function getRoleIdsByUserId(int $storeUserId): array
    {
        return (new static)->where('user_id', '=', $storeUserId)->column('role_id');
    }

    /**
     * 根据角色ID判断是否存在用户
     * @param int $roleId
     * @return bool
     * @throws DbException
     */
    public static function isExistsUserByRoleId(int $roleId): bool
    {   $where = [
            'role_id'=>$roleId,
            'is_delete'=>0
        ];
        $res = (new static)->where($where)->count();
        return $res > 0 ? true : false;
    }

    /**
     * 批量删除
     * @param array $where
     * @return false||int
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public static function setDeleteAll(array $where=[])
    {
        return (new static)->where($where)->where(['is_delete' => 0])->update(['is_delete' => 1]);
    }
}
